package GetClient;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.Socket;
import java.util.List;

public class GetClient {
    private String host;
    public GetClient(String host) {
        this.host = host;
    }

    public void sendGetRequest() throws IOException {
        int port = Integer.parseInt(host.split(":")[1]);
        String server = host.split(":")[0];

        try {
            Socket client = new Socket(server, port);
            OutputStream outToServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);
            String request = "GET /weather HTTP/1.1\r\nHost: " + server + "\r\n\r\n";
            out.writeBytes(request);

            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            String response="";
            int c = -1;
            while ((c = in.read()) != -1) {
                response += (char)c;
            }
            //get request body
            String responseBody = response.toString().split("\r\n\r\n")[1];
            //transfer request body to JSON object
            JSONArray jsonArray = JSONArray.parseArray(responseBody);
            //print JSON object
            for (Object obj : jsonArray) {
                System.out.println(obj);
            }
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
